package com.example.t470p.facechecktickets.View;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.t470p.facechecktickets.Customer.ImportText;
import com.example.t470p.facechecktickets.Customer.RotationLoadingView;
import com.example.t470p.facechecktickets.M1CardInfo;
import com.example.t470p.facechecktickets.R;
import com.example.t470p.facechecktickets.ResultCode;
import com.example.t470p.facechecktickets.Utils.CustomString;
import com.example.t470p.facechecktickets.Utils.LogUtil;
import com.example.t470p.facechecktickets.Utils.SPUtil;
import com.example.t470p.facechecktickets.Utils.ToastUtil;
import com.example.t470p.facechecktickets.Utils.pathUtils;
import com.example.t470p.facechecktickets.Utils.util;
import com.example.t470p.facechecktickets.httpUtils;
import com.example.t470p.facechecktickets.response.TicketOrCardResponse;
import com.google.gson.Gson;
import com.synjones.handsetS8.BarReaderModule;
import com.synjones.handsetS8.BarScanResult;
import com.synjones.handsetS8.IDCardReaderModule;
import com.synjones.idcard.IDCard;
import com.synjones.idcard.IDCardReaderRetInfo;
import com.synjones.m1card.M1CardReader;
import com.synjones.multireaderlib.MultiReader;

import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

public class CheckNewActivity extends Activity implements View.OnClickListener {

    private ImageView imageHead;
    private ImportText itNumber;
    private ImportText itName;
    private ImportText itResult;
    private Button scan;
    private ImageView setting;
    private TextView tvSmall;
    private TextView tvBig;
    private LinearLayout llChange;
    private static final int LLCHANGE = 20;
    private static final int ImageOk = 22;
    private boolean changeClackAble = true;
    private Thread threadIC;

    private String baseUrl;
    private String gateNumber;
    private String userName;
    private String passWord;

    private int screenWidth, screenHeight;
    int saveDate, currentDate;
    int ticketCount = 0; //检票计数
    private static final String TAG = "CheckNewActivity";
    private String M1Card1 = "";
    private int readNow = 0; //0 IC卡， 1 身份证
    private int SoundNumber = 0;
    private static final int SoundNumberTip = 21;

    private TextToSpeech mSpeech = null;
    private static float m_voice_speed = 1.0f;   //合成语音的语速
    private static float m_voice_pitch = 1.0f;   //合成语音的语调

    private boolean ConfigGateSet;
    private boolean ConfigSuccess;
    public String m_strUserName;
    public String m_strPassWord;
    public String m_Url;
    public String m_strGateNo;
    private Calendar cal;

    /****************************************************/
    /************************M1卡************************/
    boolean findingCard = false;
    private byte data[] = new byte[1024];//接收buf
    private int dataLen = 0;//接收数据长度
    IDCardReaderModule idCardReaderModule;
    public M1CardReader m1Reader;
    MultiReader multiReader;
    boolean isConnect;
    final int MESSAGE_FIND_CARD = 0x51;
    String m_strM1Card; //IC 卡号
    public int m_CheckMode;                          //1:检卡 2:检票

    public int type_QRCode = 1; //二维码卡号
    public int type_IDCard = 2; //身份证卡号
    public int type_ICCard = 3; //IC卡号

    private boolean reading = false;


    /************************扫码************************/
    BarReaderModule barReaderModule;             //扫描头
    public boolean bNeedCheckTicket = true;    //检票标志位
    private String m_StrBarCode;                //二维码号码
    public String m_UpdateBase64;              //上传的Base64图片
    public String m_UpdatePhotoPath;          //采集上传的图片路径
    public String m_UpdatePhotoName;          //采集上传的图片名称
    public String m_UpdateImgPath;            //需要上传的图片路径


    /**********************语音合成**********************/
    public String m_strStatus;
    public TextView m_Status;
    public String m_strCardNo;
    public TextView m_CardNo;
    public String m_strDate;
    public TextView m_Date;

    private static final int ReadOnceDone = 12;
    private ReadCardThread ReadCardThreadhandler;
    private String status = "";
    TicketOrCardResponse response;
    private boolean isCheck;
    public static final int CHECK_SUCCESS = 1;
    private Timer timer;
    private Timer timerB;
    private Thread thread;
    private boolean[] checkedItems;
    private RotationLoadingView mItemLoadingImage;
    private Bitmap thumbImgNow;

    //语音引擎
    private class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            // TODO Auto-generated method stub
            if (status == TextToSpeech.SUCCESS) {

                Log.i(TAG, "onInit: TTS引擎初始化成功");
            } else {
                Log.i(TAG, "onInit: TTS引擎初始化失败");
            }
        }
    }

    //    0--------接口调用成功,即检票成功
    /****************************************************/

    /**********************人脸识别**********************/
    public static final int ALGORITHM_VERSION = 1;
    private Bitmap m_FaceBmp;
    String m_FaceImgPath;
    String m_BgFacePath;
    boolean m_bFaceDetectResult = false;    //false:失败,true:成功

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_FIND_CARD:
                    Log.d(TAG, "MESSAGE_FIND_CARD");
                    if (data == null)
                        return;
                    // beep();
                    //Toast.makeText(activity, "find a Card", Toast.LENGTH_SHORT).show();
                    if (dataLen != 0) {

                        M1CardInfo m1CardInfo = new M1CardInfo(data);
                        String lM1CardNo = m1CardInfo.getCardNoStr();

                        lM1CardNo = lM1CardNo.replace("0x", "");

                        //lM1CardNo = lM1CardNo.replace(",","");

                        //翻转字符串
                        lM1CardNo = ReserveHexStr(lM1CardNo);
                        //16进制字符串转10进制字符串
                        m_strM1Card = new BigInteger(lM1CardNo, 16).toString();

                        //从服务器获取图片
//                        GetImgFromServer(m_strM1Card);

//                        checkCard_or_Ticket(type_ICCard, m_strM1Card);
                        itName.setTitleName("票名:  IC卡");
                        itNumber.setTitleName("票号:  " + m_strM1Card);     //读卡成功，显示身份证信息

//                        checkCard_or_Ticket(type_ICCard, m_strM1Card);

                        if (m_strM1Card != null && !M1Card1.equals(m_strM1Card)) {
                            M1Card1 = m_strM1Card;
//                            ShowMsg("票号:  " + m_strM1Card, 0, 0);
                            checkCard_or_Ticket(type_ICCard, m_strM1Card);

                            Message messageNumber = new Message();
                            messageNumber.what = SoundNumberTip;
                            mHandler.sendMessageDelayed(messageNumber, 3000);
                        }
                    }
                    break;

                case CHECK_SUCCESS:

                    ticketCount = ticketCount + (int) msg.obj;
                    break;
                case ReadOnceDone:  //身份证
                    Log.d(TAG, "ReadOnceDone身份证");
                    IDCard idcard = (IDCard) msg.obj;
                    if (idcard != null) {

                        itNumber.setTitleName("票号:  " + idcard.getIDCardNo());     //读卡成功，显示身份证信息

                        itName.setTitleName("票名:  身份证");

//                        checkCard_or_Ticket(type_IDCard, idcard.getIDCardNo());

                        if (idcard.getIDCardNo() != null && !M1Card1.equals(idcard.getIDCardNo())) {
                            M1Card1 = idcard.getIDCardNo();
                            checkCard_or_Ticket(type_IDCard, idcard.getIDCardNo());
                            Message messageNumber = new Message();
                            messageNumber.what = SoundNumberTip;
                            mHandler.sendMessageDelayed(messageNumber, 3000);
                        }
                    }
                    break;

                case LLCHANGE:
                    changeClackAble = true;
                    mItemLoadingImage.stopRotationAnimation();
                    mItemLoadingImage.setVisibility(View.GONE);
                    llChange.setClickable(true);
//                    int s = (int) SPUtil.get(CheckNewActivity.this, CustomString.SP_NAME, CustomString.FIRST_CHECK, 0);

                    if (readNow == 1) {
//                        SPUtil.put(CheckNewActivity.this, CustomString.SP_NAME, CustomString.FIRST_CHECK, 1);
                        tvSmall.setText("点击切换成读取IC卡");
                        tvBig.setText("身份证读取中...");
                        //打开身份证验证
                        checkIdentityCard();
                    } else {
//                        SPUtil.put(CheckNewActivity.this, CustomString.SP_NAME, CustomString.FIRST_CHECK, 0);
                        tvSmall.setText("点击切换成读取身份证");
                        tvBig.setText("IC卡读取中...");
                        //打开IC卡验证
                        checkICard();
                    }
                    break;

                case SoundNumberTip:
                    M1Card1 = "";
                    break;
                case ImageOk:
                    imageHead.setImageBitmap(thumbImgNow);
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //取消标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //取消状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_check_new);

        imageHead = (ImageView) findViewById(R.id.iv_head);
        itNumber = (ImportText) findViewById(R.id.it_number);
        itName = (ImportText) findViewById(R.id.it_name);
        itResult = (ImportText) findViewById(R.id.it_result);
        scan = (Button) findViewById(R.id.bt_scan);

        mItemLoadingImage = (RotationLoadingView) findViewById(R.id.item_loading_image);


        setting = (ImageView) findViewById(R.id.iv_setting);
        tvSmall = (TextView) findViewById(R.id.tv_change1);
        tvBig = (TextView) findViewById(R.id.tv_change2);
        llChange = (LinearLayout) findViewById(R.id.ll_change);

        //获取配置信息
//        String ConfigPath = getSDPath() + "/config.ini";
//        ConfigSuccess = GetConfig(ConfigPath);
//        if (!ConfigSuccess) {
//            ToastUtil.showToast("配置信息不完整");
//        }

        baseUrl = (String) SPUtil.get(CheckNewActivity.this, CustomString.SP_NAME, CustomString.ZYFBASEURL, "");
        gateNumber = (String) SPUtil.get(CheckNewActivity.this, CustomString.SP_NAME, CustomString.ZYFGATENUMBER, "");
        userName = (String) SPUtil.get(CheckNewActivity.this, CustomString.SP_NAME, CustomString.ZYFUSERNAME, "");
        passWord = (String) SPUtil.get(CheckNewActivity.this, CustomString.SP_NAME, CustomString.ZYFPASSWORDD, "");


        init();
    }

    @Override
    protected void onRestart() {
        super.onRestart();

        //判断优先读取项
        int s = (int) SPUtil.get(CheckNewActivity.this, CustomString.SP_NAME, CustomString.FIRST_CHECK, 0);
        if (s == 0) {
            //打开IC卡验证
            checkICard();
            readNow = 0;
        } else {
            //打开身份证验证
            checkIdentityCard();
            readNow = 1;
        }
        changeButtonString();
    }

    @Override
    protected void onStop() {
        super.onStop();

        CloseIC();
        CloseReader();
        isConnect = false;

    }

    private void init() {
        WindowManager manager = (WindowManager) getBaseContext().getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        Point point = new Point();
        if (Build.VERSION.SDK_INT < 17) {
            display.getSize(point);
        } else {
            display.getRealSize(point);
        }
        screenWidth = point.x;
        screenHeight = point.y;
        // 使用默认时区和语言环境获得一个日历
        cal = Calendar.getInstance();
        currentDate = cal.get(Calendar.DAY_OF_MONTH);
        //和当前日期不一致，清空票数
        if (saveDate != currentDate) {
            Log.d("date", "" + "clear data");
            ticketCount = 0;
        } else {
            Log.d("date", "" + "count");
        }

        scan.setEnabled(true);
        scan.setOnClickListener(this);
        setting.setOnClickListener(this);
        llChange.setOnClickListener(this);

        //M1卡初始化
        idCardReaderModule = IDCardReaderModule.getInstance(this);
        multiReader = idCardReaderModule.getBaseMultiReader();
        isConnect = idCardReaderModule.isOpen();
        if (!isConnect) {
            idCardReaderModule.open();
        }
        isConnect = idCardReaderModule.isOpen();
        if (null == m1Reader) {
            m1Reader = new M1CardReader(multiReader);
        }

        m_CheckMode = 1;

        //扫描头初始化
        m_StrBarCode = "";
        barReaderModule = BarReaderModule.getInstance(this);
        barReaderModule.open();

        m_UpdateImgPath = pathUtils.getSDPath() + "/UpdateImg.jpg";

        //获取TTS引擎
        mSpeech = new TextToSpeech(CheckNewActivity.this, new CheckNewActivity.TTSListener());

        //判断优先读取项
        int s = (int) SPUtil.get(CheckNewActivity.this, CustomString.SP_NAME, CustomString.FIRST_CHECK, 0);
        changeButtonString();

        if (s == 0) {
            //打开IC卡验证
            checkICard();
            readNow = 0;
        } else {
            //打开身份证验证
            checkIdentityCard();
            readNow = 1;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_scan:
                //红外扫描
                redScan();
                break;

            case R.id.iv_setting:
                singleDialog();
                break;
            case R.id.ll_change:
                itNumber.setTitleName("票号:  ");
                itName.setTitleName("票名:  ");
                itResult.setTitleName("结果:  ");
                //切换持续读取项
                if (changeClackAble) {
                    ShowMsg("请稍等", 0, 0);
                    llChange.setClickable(false);
                    mItemLoadingImage.setVisibility(View.VISIBLE);
                    mItemLoadingImage.startRotationAnimation();
                    readFirst(readNow);

                } else {
                    ToastUtil.showToast("数据准备中，请稍后...");
                }

                changeClackAble = false;
                Message message = new Message();
                message.what = LLCHANGE;
                mHandler.sendMessageDelayed(message, 1000);

                break;
            default:
                break;
        }
    }

    private void readFirst(int readNows) {
//        int s = (int) SPUtil.get(CheckNewActivity.this, CustomString.SP_NAME, CustomString.FIRST_CHECK, 0);
        if (readNows == 0) {
            //关闭IC卡验证
            CloseIC();
            readNow = 1;
            isConnect = false;
        } else {
            //关闭身份证验证
            readNow = 0;
            CloseReader();
        }

    }

    private void CloseIC() {

        if (m1Reader != null) {
            m1Reader = null;
        }
        if (threadIC != null) {
            threadIC.interrupt();
            threadIC = null;
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        findingCard = false;

    }

    private void singleDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(CheckNewActivity.this);
        builder.setTitle("优先读取");
        final String[] items = {"IC卡", "身份证"};// 创建一个存放选项的数组

        int s = (int) SPUtil.get(CheckNewActivity.this, CustomString.SP_NAME, CustomString.FIRST_CHECK, 0);
        // 存放选中状态，true为选中
        checkedItems = new boolean[]{false, false};

//        final boolean[] checkedItems = {true, false};// 存放选中状态，true为选中
        // ，false为未选中，和setSingleChoiceItems中第二个参数对应
        // 为对话框添加单选列表项
        // 第一个参数存放选项的数组，第二个参数存放默认被选中的项，第三个参数点击事件
        builder.setSingleChoiceItems(items, s, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                for (int i = 0; i < checkedItems.length; i++) {
                    checkedItems[i] = false;
                }
                checkedItems[arg1] = true;
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                arg0.dismiss();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                String str = "";
                for (int i = 0; i < checkedItems.length; i++) {
                    if (checkedItems[i]) {
                        str = items[i];
                    }
                }
                if (str.equals("IC卡")) {
                    SPUtil.put(CheckNewActivity.this, CustomString.SP_NAME, CustomString.FIRST_CHECK, 0);
                } else {
                    SPUtil.put(CheckNewActivity.this, CustomString.SP_NAME, CustomString.FIRST_CHECK, 1);
                }
//                changeButtonString();
            }
        });
        builder.create().show();


    }

    private void changeButtonString() {
        int s = (int) SPUtil.get(CheckNewActivity.this, CustomString.SP_NAME, CustomString.FIRST_CHECK, 0);
        if (s == 0) {
            tvSmall.setText("点击切换成读取身份证");
            tvBig.setText("IC卡读取中...");
        } else {
            tvSmall.setText("点击切换成读取IC卡");
            tvBig.setText("身份证读取中...");
        }

    }

    private void redScan() {
        m_CheckMode = 2;

        barReaderModule.scan(new BarReaderModule.OnScanResult() {
            @Override
            public void onScanResult(BarScanResult barScanResult) {
                if (barScanResult.code != 0) {
                    ShowMsg("扫码失败", 0, 0);

                    return;
                } else {

                    int end_pos = barScanResult.barMsg.lastIndexOf("\r\n");

                    if (0 > end_pos) {
                        m_StrBarCode = barScanResult.barMsg;
                    } else {
                        m_StrBarCode = barScanResult.barMsg.substring(0, end_pos);
                    }
                    if (m_StrBarCode != null && !m_StrBarCode.equals("") && !m_StrBarCode.equals("0")) {
//                        ShowMsg(m_StrBarCode, 1, 0);
                        //ShowMsg("扫码成功",0,0);
                        //检票(二维码)
//                        CheckBarCodeTicket();
                        m_StrBarCode = m_StrBarCode.replaceAll("\r|\n", "");
                        checkCard_or_Ticket(type_QRCode, m_StrBarCode);
                        itName.setTitleName("票名: 扫码检票");
                        itNumber.setTitleName("票号:  " + m_StrBarCode);
                        Log.d(TAG, "onScanResult: 扫码成功");

                    } else {
                        ShowMsg("扫码为空", 0, 0);
                        bNeedCheckTicket = true;

                    }
                }
            }
        });

    }


    private void checkIdentityCard() {
        if (reading == false) {
            startReadThread();
        }
    }


    void startReadThread() {
        reading = true;
        ReadCardThreadhandler = new ReadCardThread();
        ReadCardThreadhandler.start();
    }

    private void checkICard() {

        m_CheckMode = 1;
        FindCardAll();

    }

    private void FindCardAll() {

        findingCard = true;
        if (findingCard) {
            long t = System.currentTimeMillis();
            idCardReaderModule = IDCardReaderModule.getInstance(this);
            multiReader = idCardReaderModule.getBaseMultiReader();
            isConnect = idCardReaderModule.isOpen();
            if (!isConnect) {
                idCardReaderModule.open();
            }
            isConnect = idCardReaderModule.isOpen();
            if (null == m1Reader) {
                m1Reader = new M1CardReader(multiReader);
            }

            util.sleep(50);//如果超时，则重新打开读卡器
            if (System.currentTimeMillis() - t > 2000 || !isConnect) {
                t = System.currentTimeMillis();
                idCardReaderModule = IDCardReaderModule.getInstance(this);
                multiReader = idCardReaderModule.getBaseMultiReader();
                if (!isConnect) {
                    idCardReaderModule.open();
                }
                isConnect = idCardReaderModule.isOpen();

            }
        }

        threadIC = new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub


                byte recv[] = null;
                int findTimes = 0;
                dataLen = 0;
                //multiReader.EnterWorkMode();
                while (findingCard) {
                    recv = m1Reader.findM1Card();
                    if (recv != null) {
                        findTimes++;
                        if (findTimes >= 3) {//连续3次读卡成功 认为寻卡成功
                            System.arraycopy(recv, 0, data, 0, recv.length);
                            dataLen = recv.length;
                            mHandler.sendEmptyMessage(MESSAGE_FIND_CARD);
                            findTimes = 0;
//                            break;
                        }
                        recv = null;
                        util.sleep(100);
                    } else {
                        findTimes = 0;
                    }
//                    if (recv == null) {
//                        mHandler.sendEmptyMessage(MESSAGE_FIND_CARD);
//                    }

                }
            }

        });
        threadIC.start();
    }


    //读卡线程
    class ReadCardThread extends Thread {
        public void run() {
            OpenReader();
            Log.d(TAG, "run: ReadCardThread");
            long t = System.currentTimeMillis();
            while (reading) {//读卡器上电需要时间，通过获取samvid判断读卡器是否已工作
                String samvID = idCardReaderModule.getSamvIDString();
                if (samvID != null && samvID.length() > 0)
                    break;
                util.sleep(50);//如果超时，则重新打开读卡器
                if (System.currentTimeMillis() - t > 2000) {
                    t = System.currentTimeMillis();
                    idCardReaderModule.close();
                    idCardReaderModule.open();
                }
            }
            while (reading) {
                try {
                    //getIDcardInfo()只读身份证信息，不读取指纹信息。 等同于getIDcardInfo(false, true, false);
                    IDCardReaderRetInfo retInfo;
//                    if(!boolReadFringerprint)//是否需要读指纹
                    retInfo = idCardReaderModule.getIDcardInfo();
//                    else
//                        retInfo = idCardReaderModule.getIDcardInfo(false,true,true);

                    //读取指纹信息，读卡时间会稍长  可参考指纹的activity中读取身份证指纹按钮的实现
                    //IDCardReaderRetInfo retInfo = idCardReaderModule.getIDcardInfo(boolSameCardReadOnce, boolDecodePhoto, boolReadFringerprint);
                    //samvID=idCardReaderModule.getSamvIDString();//获取公安部二代证模块编号
                    //String appendAddress=idCardReaderModule.getAppendAddress();//获取身份证内的追加地址信息
                    if (retInfo.errCode == IDCardReaderRetInfo.ERROR_OK) {
//                        if(boolReadFringerprint) {//仅测试时读取追加信息
//                            retInfo.card.setAppendAddress(idCardReaderModule.getAppendAddress());
//                        }
                        mHandler.obtainMessage(ReadOnceDone, retInfo.card).sendToTarget();
                        status = "";
                        Thread.sleep(500);
                    } else {
                        status = util.bytesToHexString(new byte[]{retInfo.sw1, retInfo.sw2, retInfo.sw3});
                        mHandler.obtainMessage(ReadOnceDone, null).sendToTarget();
                        Thread.sleep(200);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }//while

//            mHandler.obtainMessage(ReadThreadDone).sendToTarget();

        }//run

        public void StopRead() {
            reading = false;
            interrupted();
            try {
                join(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    /**
     * 打开读卡器
     *
     * @Title OpenReader
     */
    private void OpenReader() {
        if (!idCardReaderModule.isOpen())
            idCardReaderModule.open();
    }

    /**
     * 关闭读卡器
     *
     * @Title CloseReader
     */
    private void CloseReader() {
        //停止读卡线程
        if (ReadCardThreadhandler != null) {
            ReadCardThreadhandler.StopRead();
            ReadCardThreadhandler = null;
        }
        idCardReaderModule.close();
    }


    /**
     * 寻卡
     */
    public void FindCard(final int timeout) {

        //M1卡初始化
        idCardReaderModule = IDCardReaderModule.getInstance(this);
        multiReader = idCardReaderModule.getBaseMultiReader();
        isConnect = idCardReaderModule.isOpen();
        if (!isConnect) {
            idCardReaderModule.open();
        }
        isConnect = idCardReaderModule.isOpen();
        if (null == m1Reader) {
            m1Reader = new M1CardReader(multiReader);
        }


        findingCard = true;
        threadIC = new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                byte recv[] = null;
                int findTimes = 0;
                long t = System.currentTimeMillis();
                dataLen = 0;
                //multiReader.EnterWorkMode();
                while (findingCard && System.currentTimeMillis() - t < timeout && recv == null) {
                    recv = m1Reader.findM1Card();
                    if (recv != null) {
                        findTimes++;
                        if (findTimes >= 3) {//连续3次读卡成功 认为寻卡成功
                            System.arraycopy(recv, 0, data, 0, recv.length);
                            dataLen = recv.length;
                            mHandler.sendEmptyMessage(MESSAGE_FIND_CARD);
                            break;
                        }
                        recv = null;
                        util.sleep(10);
                    } else {
                        findTimes = 0;
                    }
                }
                findingCard = false;
                if (recv == null) {
                    mHandler.sendEmptyMessage(MESSAGE_FIND_CARD);
                }
            }
        });
        threadIC.start();
    }

    //一直寻卡
    private void FindCardAlways() {

        Log.d(TAG, "FindCardAlways: ");
        if (timer == null) {
            timer = new Timer();
        }

        //M1卡初始化
        idCardReaderModule = IDCardReaderModule.getInstance(this);
        multiReader = idCardReaderModule.getBaseMultiReader();
        isConnect = idCardReaderModule.isOpen();
        if (!isConnect) {
            idCardReaderModule.open();
        }
        isConnect = idCardReaderModule.isOpen();
        if (null == m1Reader) {
            m1Reader = new M1CardReader(multiReader);
        }

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                byte recv[] = null;
                int findTimes = 0;
                long t = System.currentTimeMillis();
                dataLen = 0;
                //multiReader.EnterWorkMode();
                while (recv == null) {
                    recv = m1Reader.findM1Card();
                    if (recv != null) {
                        findTimes++;
                        if (findTimes >= 3) {//连续3次读卡成功 认为寻卡成功
                            System.arraycopy(recv, 0, data, 0, recv.length);
                            dataLen = recv.length;
                            mHandler.sendEmptyMessage(MESSAGE_FIND_CARD);
                            break;
                        }
                        recv = null;
                        util.sleep(10);
                    } else {
                        findTimes = 0;
                    }
                }
                if (recv == null) {
                    mHandler.sendEmptyMessage(MESSAGE_FIND_CARD);
                }

            }
        }, 0, 3000);

    }

    /*
     * 显示信息(0:Status,1:CardNo,2:Date)
     */
    public void ShowMsg(String Msg, int type, int PlayOrNot) {
        switch (type) {
            case 0:
                m_strStatus = Msg;
                if (0 == PlayOrNot) {
                    //播放声音
                    PlayAudioFile(Msg);
                } else {
                    itResult.post(new Runnable() {
                        @Override
                        public void run() {
                            itResult.setTitleName("结果:  " + m_strStatus);
                            PlayAudioFile(m_strStatus);
                        }
                    });
                }
                break;
            case 1:
                m_strCardNo = Msg;
                itName.post(new Runnable() {
                    @Override
                    public void run() {
                        PlayAudioFile(m_strCardNo);
                    }
                });
                break;
            case 2:
                m_strDate = Msg;
                m_Date.post(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
                break;
        }
    }

    //播放合成语音
    public void PlayAudioFile(String str) {
        //设置中文
        int supported = mSpeech.setLanguage(Locale.CHINESE);
        mSpeech.setSpeechRate(m_voice_speed);
        mSpeech.setPitch(m_voice_pitch);

        if ((supported != TextToSpeech.LANG_AVAILABLE) && (supported != TextToSpeech.LANG_COUNTRY_AVAILABLE)) {
            //语言设置失败
            Log.i(TAG, "中文设置失败");
        } else {
            Log.i(TAG, "中文设置成功");
        }
        //mSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, null);
        mSpeech.speak(str, TextToSpeech.QUEUE_ADD, null);
    }

    /*
     * 16进制大小端调整
     */
    public String ReserveHexStr(String Hex) {
        String ret = "";
        int begin = 0;
        int end = Hex.indexOf(",", begin);
        List list = new ArrayList();
        while (true) {
            if (-1 == end) {
                break;
            }
            String test = Hex.substring(begin, end);
            list.add(test);
            begin = end + 1;
            end = Hex.indexOf(",", begin);
        }

        for (int index = list.size() - 1; index >= 0; index--) {
            if (index < 0) {
                break;
            }
            String ltest = list.get(index).toString();
            ret += ltest;
        }

        return ret;
    }

    /*
     * 检票或检卡
     * */
    public void checkCard_or_Ticket(final int type, final String typeData) {
        imageHead.setImageResource(R.drawable.photo);
        new Thread(new Runnable() {
            @Override
            public void run() {

                // 先封装一个 JSON 对象
                JSONObject param = new JSONObject();

                try {
                    param.put("searchDataType", type);
                    param.put("searchData", typeData);
                    param.put("checkCount", -1);
                    param.put("gateNo", gateNumber);
                    param.put("isCollectionGate", "N");
                    param.put("sign", "A96D48AE69F46BD0E1B17F10316086F3");
                    param.put("timestamp", "20180611165000");


//                    String ss = httpUtils.postJson(BaseUrl.check_Ticket_or_Card, param);
                    String url = "http://" + baseUrl + "/jsonrequest/v1_0/checkFaceTicketInterface/checkTicket.json";
                    String ss = httpUtils.postJson(url, param);
                    response = new Gson().fromJson(ss, TicketOrCardResponse.class);
                    LogUtil.d(response.toString());
                    isCheck = true;
                    int result1 = Integer.valueOf(response.getCode());
//                result = 100010;
//                    if (result1 != 0) {
//                        itResult.setTitleName("结果:  " + response.getMessage());
////                        ShowMsg(response.getMessage(),0,0);
//                    }
                    switch (result1) {
                        case ResultCode.SUCCESS:
                            try {
                                int result = response.getData().getPassPersonSum();
                                Message message = new Message();
                                message.obj = result;
                                message.what = CHECK_SUCCESS;
                                mHandler.sendMessage(message);
                                final String SoundName = response.getData().getGateSoundName();
                                final int PersonAll = response.getData().getPassPersonSum();
                                ShowMsg(SoundName + ", 可通行" + PersonAll + "人", 0, 1);

                                //返回成功后查看是否有图片
                                if (response.getData().getBase64Pic() != null) {
                                    byte[] decodedString = Base64.decode((String) response.getData().getBase64Pic(), Base64.DEFAULT);
                                    Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

//                                    Log.d("zyf1", getBitmapSize(decodedByte));
                                    thumbImgNow = Bitmap.createScaledBitmap(decodedByte, 100, 100, true);
//                                    Log.d("zyf2", getBitmapSize(thumbImgNow));

                                    mHandler.sendEmptyMessage(ImageOk);
//                                    decodedByte = null;
                                }
                            } catch (Exception e) {
                                LogUtil.d("返回成功，解析异常");
                            }

                            break;
                        case ResultCode.CHECKED:
                            ShowMsg(response.getData().getGateSoundName(), 0, 1);
                            break;
                        case ResultCode.SYSTEM_ERROR:

                            ShowMsg(response.getData().getGateSoundName(), 0, 1);
                            break;
                        case ResultCode.TO_COLLECT_INFORMATION:

                            LogUtil.d("采集信息");
//                        mHandler.sendEmptyMessage(COLLECT_INFORMATION);

                            ShowMsg(response.getMessage(), 0, 1);
                            break;
                        case ResultCode.TO_COMPARE:
//                        LogUtil.d("人脸识别");
//                        Message msg =new Message();
//                        msg.obj = type;
//                        msg.what=COMPARE_FACE;   //标志消息的标志
//                        mHandler.sendMessage(msg);

                            ShowMsg(response.getMessage(), 0, 1);
                            break;
                        case ResultCode.CHECK_TIME_BETWEEN_IS_NOT_ENOUGH:


                            ShowMsg(response.getMessage(), 0, 1);
                            break;
                        case ResultCode.TIME_IS_INVAIBLE:


                            ShowMsg(response.getMessage(), 0, 1);
                            break;
                        case ResultCode.TIME_IS_INVAIBLE2:


                            ShowMsg(response.getMessage(), 0, 1);
                            break;
                        case ResultCode.UPLOAD_MESSAGE_FAIED:


                            ShowMsg(response.getMessage(), 0, 1);
                            break;
                        case ResultCode.OUT_DATE:


                            ShowMsg(response.getMessage(), 0, 1);
                            break;
                        case ResultCode.QRCODE_IS_NOT_EXIST:


                            ShowMsg(response.getMessage(), 0, 1);
                            break;
                        case ResultCode.TODAY_COUNT_EXHAUST:


                            ShowMsg(response.getMessage(), 0, 1);
                            break;
                        case ResultCode.Card_IS_NOT_EXIST:

                            ShowMsg(response.getMessage(), 0, 1);
                            break;
                        default:
//                            setBtn();
                            ShowMsg(response.getMessage(), 0, 1);
                            ToastUtil.showToast(response.getMessage());
                            break;
                    }

                } catch (Exception e) {
                    ToastUtil.showToast("checkCard_or_Ticket异常：网络请求失败");

                }
            }
        }).start();

    }

    /*
     * 获取SD卡路径
     */
    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }

    /*
     * 获取配置信息
     */
    public boolean GetConfig(String ConfigPath) {
        boolean ret = false;
        try {
            FileInputStream fis = null; // 读
            Properties pp;

            pp = new Properties();
            fis = new FileInputStream(ConfigPath);
            pp.load(fis);

            m_Url = pp.get("SericeUrl").toString();

            m_strGateNo = pp.get("GateNO").toString();// 获取配置文件的Gps_device字段的信息，既它=号后面的数据

            if (null != m_strGateNo && !TextUtils.isEmpty(m_strGateNo)) {
                ConfigGateSet = true;
            } else {
                ConfigGateSet = false;
            }

            m_strUserName = pp.get("UserName").toString();

            m_strPassWord = pp.get("PassWord").toString();

            ret = true;
        } catch (Exception e) {
            e.printStackTrace();
            ret = false;
        }
        return ret;
    }

    /**
     * 得到bitmap的大小
     */
    public static String getBitmapSize(Bitmap bitmap) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {    //API 19
//            return String.valueOf(bitmap.getAllocationByteCount());
//        }
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {//API 12
//            return String.valueOf(bitmap.getByteCount());
//        }

        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int size = bitmap.getRowBytes() * bitmap.getHeight();
        int digitGroups = (int) (Math.log10(bitmap.getRowBytes() * bitmap.getHeight()) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
        // 在低版本中用一行的字节x高度

    }
}
